package com.huawei.demo;

import com.huaweicloud.sdk.ccm.v1.CcmClient;
import com.huaweicloud.sdk.ccm.v1.model.CertDistinguishedName;
import com.huaweicloud.sdk.ccm.v1.model.CreateCertificateRequest;
import com.huaweicloud.sdk.ccm.v1.model.CreateCertificateRequestBody;
import com.huaweicloud.sdk.ccm.v1.model.CreateCertificateResponse;
import com.huaweicloud.sdk.ccm.v1.model.ExtendedKeyUsage;
import com.huaweicloud.sdk.ccm.v1.model.RevokeCertificateRequest;
import com.huaweicloud.sdk.ccm.v1.model.ShowCertificateRequest;
import com.huaweicloud.sdk.ccm.v1.model.ShowCertificateResponse;
import com.huaweicloud.sdk.ccm.v1.model.SubjectAlternativeName;
import com.huaweicloud.sdk.ccm.v1.model.Validity;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;
import java.util.ArrayList;
import java.util.List;

public class CertificateManagerDemo {

    public static void main(String[] args) {

        /*
         * 基础认证信息：
         * - ak: 华为云账号Access Key
         * - sk: 华为云账号Secret Access Key
         * - domainId: 华为云账号ID 详情见https://support.huaweicloud.com/productdesc-iam/iam_01_0023.html
         * - ccmEndpoint: 华为云CCM服务(PCA属于CCM下的微服务)的访问终端地址
         */
        String ak = "<AccessKey>";
        String sk = "<SecretAccessKey>";
        String domainId = "<DomainID>";
        String ccmEndpoint = "<CcmEndpoint>";

        // 1.准备访问华为云的认证信息，PCA为全局服务
        final GlobalCredentials auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk)
                .withDomainId(domainId);

        // 2.初始化SDK，传入认证信息及CCM服务的访问终端地址
        final CcmClient ccmClient = CcmClient.newBuilder()
                .withCredential(auth)
                .withEndpoint(ccmEndpoint).build();

        // 3.申请终端实体证书
        // 用于签发证书的CA的证书id
        String issuerId = "3a02c7f6-d8f5-497e-9f60-18dfd3eeb4e6";
        String certId = applyCert(ccmClient, issuerId);
        if (certId == null) {
            return;
        }

        // 4.查看证书详情
        ShowCertificateResponse response = showCert(ccmClient, certId);
        if (response != null) {
            // 查看证书的签名算法与状态
            System.out.println(response.getKeyAlgorithm());
            System.out.println(response.getStatus());

            // 5.吊销证书,发生错误将会抛异常
            revokeCert(ccmClient, certId);
        }
    }

    private static String applyCert(CcmClient ccmClient, String issuerId) {
        // （1）证书密钥算法
        String keyAlgorithm = "RSA2048";
        // （2）签名哈希算法
        String signatureAlgorithm = "SHA512";

        /*
         * （3）证书有效期定义
         * - type: 时间类型，可选："YEAR"、"MONTH"、”DAY“、"HOUR"
         * - value: 对应的值
         */
        Validity validity = new Validity();
        validity.setType("MONTH");
        validity.setValue(2);

        /*
         * （4）定义CA证书的唯一标识信息
         * - organization: 组织名称
         * - organizationalUnit: 部门名称
         * - country: 国家缩写，仅限两个字符，如中国-CN
         * - state: 省市名称
         * - locality: 城市名称
         * - commonName: 证书域名或IP
         */
        CertDistinguishedName subjectInfo = new CertDistinguishedName();
        subjectInfo.setOrganization("your organization");
        subjectInfo.setOrganizationalUnit("your organizational unit");
        subjectInfo.setCountry("CN");
        subjectInfo.setState("your state");
        subjectInfo.setLocality("your locality");
        subjectInfo.setCommonName("your dns");

        /*
         * （5）密钥用法，服务器证书通常只赋予keyAgreement与digitalSignature，为可选值
         * - digitalSignature : 数字签名；
         * - nonRepudiation : 不可抵赖；
         * - keyEncipherment : 密钥用于加密密钥数据；
         * - dataEncipherment : 用于加密数据；
         * - keyAgreement : 密钥协商；
         * - keyCertSign : 签发证书；
         * - cRLSign : 签发吊销列表；
         * - encipherOnly : 仅用于加密；
         * - decipherOnly : 仅用于解密。
         */
        List<String> keyUsages = new ArrayList<>();
        keyUsages.add("digitalSignature");
        keyUsages.add("keyAgreement");

        /*
         * （6）主体备用名称: 暂时支持DNS、IP、URI与EMAIL，为可选值
         *  SubjectAlternativeName：
         *         type：类型
         *         value：对应值
         */
        List<SubjectAlternativeName> subjectAlternativeName = new ArrayList<>();
        // a、添加备用DNS
        SubjectAlternativeName alterNameDNS = new SubjectAlternativeName();
        alterNameDNS.setType("DNS");
        alterNameDNS.setValue("*.example.com");
        subjectAlternativeName.add(alterNameDNS);
        // b、添加备用IP
        SubjectAlternativeName alterNameIP = new SubjectAlternativeName();
        alterNameIP.setType("IP");
        alterNameIP.setValue("127.0.0.1");
        subjectAlternativeName.add(alterNameIP);
        // b、添加备用email
        SubjectAlternativeName alterNameEmail = new SubjectAlternativeName();
        alterNameEmail.setType("EMAIL");
        alterNameEmail.setValue("myEmail@qq.com");
        subjectAlternativeName.add(alterNameEmail);
        ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage();
        extendedKeyUsage.setClientAuth(true);
        extendedKeyUsage.setServerAuth(true);

        // （7）请求体各属性赋值
        // 各属性的取值约束，请查阅：https://support.huaweicloud.com/api-ccm/CreateCertificate.html
        CreateCertificateRequestBody requestBody = new CreateCertificateRequestBody();
        requestBody.setIssuerId(issuerId);
        requestBody.setKeyAlgorithm(keyAlgorithm);
        requestBody.setSignatureAlgorithm(signatureAlgorithm);
        requestBody.setValidity(validity);
        requestBody.setDistinguishedName(subjectInfo);
        requestBody.setKeyUsages(keyUsages);
        requestBody.setSubjectAlternativeNames(subjectAlternativeName);
        requestBody.setExtendedKeyUsage(extendedKeyUsage);

        // 4、构造请求体
        CreateCertificateRequest request = new CreateCertificateRequest()
                .withBody(requestBody);

        // 5、开始发起请求
        CreateCertificateResponse response;
        try {
            response = ccmClient.createCertificate(request);
        } catch (Exception e) {
            System.out.println("error info: " + e.getMessage());
            return null;
        }

        // 6、获取响应消息
        String certId = response.getCertificateId();
        System.out.println(certId);
        return certId;
    }

    private static ShowCertificateResponse showCert(CcmClient ccmClient, String certId) {
        ShowCertificateRequest request = new ShowCertificateRequest().withCertificateId(certId);
        try {
            return ccmClient.showCertificate(request);
        } catch (Exception e) {
            System.out.println("error info: " + e.getMessage());
            return null;
        }
    }

    private static void revokeCert(CcmClient ccmClient, String certId) {
        RevokeCertificateRequest request = new RevokeCertificateRequest().withCertificateId(certId);
        try {
            ccmClient.revokeCertificate(request);
        } catch (Exception e) {
            System.out.println("error info: " + e.getMessage());
        }
    }

}
